const express = require('express');  
const router = express.Router();  
const multiparty = require('multiparty');  
let { imgmodel } = require('../moduls/db'); // 确保数据库模型已正确引入  

// 上传  
router.post('/add_img', async (req, res, next) => {  
    let form = new multiparty.Form();  
    form.uploadDir = 'upload'; // 确保该目录存在且可写  
    form.parse(req, async (err, fields, files) => {  
        if (err) {  
            console.error('文件上传错误:', err);  
            return res.status(500).send({  
                error: '文件上传失败'  
            });  
        }  
        try {  
            const imgPath = "http://localhost:3000/" + files.file[0].path;  
            await imgmodel.create({ imgs: imgPath });  
            res.send({  
                path: imgPath  
            });  
        } catch (error) {  
            console.error('保存图片失败:', error);  
            res.status(500).send({  
                error: '保存图片失败'  
            });  
        }  
    });  
});  

// 获取最新图片  
router.get('/get', async (req, res) => {  
    try {  
        let data = await imgmodel.find();  
        let index = data.length - 1;  
        console.log(data[index].imgs);  
        res.send({  
            imgurl: data[index].imgs  
        });  
    } catch (error) {  
        console.error('获取图片失败:', error);  
        res.status(500).send({  
            error: '获取图片失败'  
        });  
    }  
});  

module.exports = router;